package com.gzwanchuang.xhgj.ui.page.home;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.gzwanchuang.architecture.utils.GsonUtils;
import com.gzwanchuang.architecture.utils.ValidateUtils;
import com.gzwanchuang.xhgj.BuildConfig;
import com.gzwanchuang.xhgj.R;
import com.gzwanchuang.xhgj.bridge.data.repository.Apis;
import com.gzwanchuang.xhgj.bridge.data.repository.WebApis;
import com.gzwanchuang.xhgj.bridge.request.HomeRequestViewModel;
import com.gzwanchuang.xhgj.bridge.state.home.KaBaoViewModel;
import com.gzwanchuang.xhgj.databinding.FragmentKaBaoBinding;
import com.gzwanchuang.xhgj.net.NetworkManager;
import com.gzwanchuang.xhgj.net.interfaces.OnRequestCallBack;
import com.gzwanchuang.xhgj.proto.Merchantservice;
import com.gzwanchuang.xhgj.ui.base.BaseFragment;
import com.gzwanchuang.xhgj.ui.dialog.RecycleViewDialog;
import com.gzwanchuang.xhgj.ui.dialog.SelectRenDialog;
import com.google.protobuf.InvalidProtocolBufferException;
import com.gzwanchuang.xhgj.ui.web.ui.WebViewActivity;

import java.util.List;

import kale.ui.view.dialog.EasyDialog;

/**
 * 文件名 : HomeRootFragment
 * 创建者 : MangoWang
 * 创建日期 : 2019/12/24 16:20
 * 微信 : MangoWaWang
 * 邮箱 : 763482205@qq.com
 * 描述 : TODO
 */
public class KaBaoFragment extends BaseFragment {


    private FragmentKaBaoBinding mBinding;
    private KaBaoViewModel mViewModel;
    private HomeRequestViewModel mRequestViewModel;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(KaBaoViewModel.class);
        mRequestViewModel = ViewModelProviders.of(this).get(HomeRequestViewModel.class);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_ka_bao, container, false);
        mBinding = FragmentKaBaoBinding.bind(view);
        mBinding.setClick(new ClickProxy());
        mViewModel.layoutManager.set(new LinearLayoutManager(mActivity));
        mBinding.setVm(mViewModel);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRequestViewModel.getErrorString().observe(this, s -> {
            hideProgress();
            showShortToast(s);
        });
        mRequestViewModel.getResultString().observe(this, s -> {
            hideProgress();
            showShortToast(s);
        });

        NetworkManager.INSTANCE.post(Apis.card_bag, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                Merchantservice.card_bag rep = Merchantservice.card_bag.parseFrom(response);
                List<Merchantservice.card> bankList = rep.getCardsList();
                int cdnumberTi = 0;
                int cdnumberVip = 0;
                int bankNumber = 0;
                for (Merchantservice.card item :
                        bankList) {
                    if (item.getType().equals("CREDIT")) {
                        if (item.getIsVip().equals("1")) {
                            cdnumberVip++;
                        } else if (item.getIsVip().equals("0")) {
                            cdnumberTi++;
                        }
                    } else {
                        bankNumber++;
                    }
                }
                mBinding.tvAllNumber.setText("我的银行卡(共" + bankList.size() + "张)");
                mBinding.tvNumber.setText("提额(" + cdnumberTi + ")/" + "享惠(" + cdnumberVip + ")/" + "其他(" + bankNumber + ")");
                mViewModel.adapter.get().replaceData(bankList);
                int size = bankList.size();
                if (size < 10) {
                    mViewModel.adapter.get().getLoadMoreModule().loadMoreEnd();
                } else {
                    mViewModel.adapter.get().getLoadMoreModule().loadMoreComplete();
                }
            }

            @Override
            public void onError(int errorCode, String errorMessage) {

                if (errorCode==200)
                {
                    int cdnumberTi = 0;
                    int cdnumberVip = 0;
                    int bankNumber = 0;
                    mBinding.tvAllNumber.setText("我的银行卡(共" + 0 + "张)");
                    mBinding.tvNumber.setText("提额(" + cdnumberTi + ")/" + "享惠(" + cdnumberVip + ")/" + "其他(" + bankNumber + ")");
                    mViewModel.adapter.get().replaceData(null);
                }
            }
        });
        mViewModel.adapter.get().addChildClickViewIds(R.id.tv_jie_bang);
        mViewModel.adapter.get().setOnItemChildClickListener((adapter, view1, position) -> {
            if (view1.getId() == R.id.tv_jie_bang) {
                unbindCard(view1.getTag().toString());
            }
        });
    }

    private void unbindCard(String id) {

        Merchantservice.card_unbind.Builder builder = Merchantservice.card_unbind.newBuilder();
        builder.setId(id);
        NetworkManager.INSTANCE.post(Apis.card_unbind, builder.build().toByteArray(),new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) {

            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                if (errorCode == 200) {
                    showShortToast(errorMessage);
                    NetworkManager.INSTANCE.post(Apis.card_bag, new OnRequestCallBack() {
                        @Override
                        public void onOk(byte[] response) throws InvalidProtocolBufferException {
                            Merchantservice.card_bag rep = Merchantservice.card_bag.parseFrom(response);
                            List<Merchantservice.card> bankList = rep.getCardsList();
                            int cdnumberTi = 0;
                            int cdnumberVip = 0;
                            int bankNumber = 0;
                            for (Merchantservice.card item :
                                    bankList) {
                                if (item.getType().equals("CREDIT")) {
                                    if (item.getIsVip().equals("1")) {
                                        cdnumberVip++;
                                    } else if (item.getIsVip().equals("0")) {
                                        cdnumberTi++;
                                    }
                                } else {
                                    bankNumber++;
                                }
                            }
                            mBinding.tvAllNumber.setText("我的银行卡(共" + bankList.size() + "张)");
                            mBinding.tvNumber.setText("提额(" + cdnumberTi + ")/" + "享惠(" + cdnumberVip + ")/" + "其他(" + bankNumber + ")");
                            mViewModel.adapter.get().replaceData(bankList);
                            int size = bankList.size();
                            if (size < 10) {
                                mViewModel.adapter.get().getLoadMoreModule().loadMoreEnd();
                            } else {
                                mViewModel.adapter.get().getLoadMoreModule().loadMoreComplete();
                            }
                        }

                        @Override
                        public void onError(int errorCode, String errorMessage) {


                            if (errorCode==200)
                            {
                                int cdnumberTi = 0;
                                int cdnumberVip = 0;
                                int bankNumber = 0;
                                mBinding.tvAllNumber.setText("我的银行卡(共" + 0 + "张)");
                                mBinding.tvNumber.setText("提额(" + cdnumberTi + ")/" + "享惠(" + cdnumberVip + ")/" + "其他(" + bankNumber + ")");
                                mViewModel.adapter.get().replaceData(null);
                            }
                        }
                    });
                }
            }
        });

    }

    @Override
    public void loadInitData() {
        super.loadInitData();
    }

    public class ClickProxy {
        public void back() {
            nav().navigateUp();
        }


        public void right() {
            WebViewActivity.startActivity(mActivity, BuildConfig.SERVERHEAD + WebApis.appeal);
        }

        public void itemOnClick(int position) {
        }

        public void loadMoreListener() {

        }

        public void bindCard() {
//            nav().navigate(R.id.action_kaBaoFragment_to_bindXinCardFragment);


            SelectRenDialog.Builder builder = new SelectRenDialog.Builder(mActivity);
            builder.setListen(new SelectRenDialog.OnDialogClickListener() {
                @Override
                public void onClickOne() {
                    nav().navigate(R.id.action_kaBaoFragment_to_bankCardRenFragment);
                }

                @Override
                public void onClickTwo() {
                    nav().navigate(R.id.action_kaBaoFragment_to_tiErRenFragment);
                }
            });
            SelectRenDialog dialog = builder.build();
            dialog.setCancelable(true);
            dialog.show(getChildFragmentManager());
        }

        public void showBank() {
            if (ValidateUtils.isValidate(mViewModel.banks)) {
                RecycleViewDialog.Builder builder = new RecycleViewDialog.Builder(mActivity);
                builder.setData(GsonUtils.serializedToJson(mViewModel.banks)).setTitle("VIP收款支持银行");
                EasyDialog build = builder.build();
                build.show(getChildFragmentManager());
            } else {
                showShortToast("暂无支持银行");
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
//            showProgress();
//            mRequestViewModel.get_xin_yong_bank("2", "2");  // 获取信用
        }
    }
}
